package rs.pnv.bank.handler;

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.ws.handler.LogicalHandler;
import javax.xml.ws.handler.LogicalMessageContext;
import javax.xml.ws.handler.MessageContext;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import rs.pnv.util.doc.DocumentUtil;
import rs.pnv.util.xmlsec.Encrypt;

public class CryptoHandler implements LogicalHandler<LogicalMessageContext> {

	@Override
	public boolean handleMessage(LogicalMessageContext context) {
		
		System.out.println("CryptoHandler.handleMessage()");

		Boolean isResponse = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

		Source source = context.getMessage().getPayload();
	
		if (isResponse) {
			System.out.println("kriptovanje...");
			Source newSource = encryptMessage(source);
			context.getMessage().setPayload(newSource);
			
			return true;
		} else {
			System.out.println("dekriptovanje...");

			return true;
		}

	}

	@Override
	public boolean handleFault(LogicalMessageContext context) {

		// ako vraća false, znači da NE treba da se pozove handleFault metoda od sledećeg handler-a.
		// dakle, vratiti true, ako POSTOJI greška.
		return true;
	}

	@Override
	public void close(MessageContext context) {
		// TODO Auto-generated method stub

	}
	
	
	private Source encryptMessage(Source source) {
		 //signDocUtil.docSignature(document, "/security/BankA.jks", "BankA", "/security/BankA.cer");
		 Encrypt encrypt = new Encrypt();
		 Document document = DocumentUtil.convertToDocument(source);
		 Document encryptDocument = encrypt.docEncryption(document, "/security/PCC.cer");
		 DocumentUtil.printDocument(encryptDocument);
		 Source encryptSource = new  DOMSource(encryptDocument);
		 
		 return encryptSource;
	}

}
